/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */


var EXPORTED_SYMBOLS =
[
    "PreferenceProxy",
    "PreferencesProxy"
];

const Ci = Components.interfaces;
const Cu = Components.utils;

Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

Cu.import("resource://savefileto/common.jsm");


function prefGetter(prefs, name)
{
    switch (prefs.getPrefType(name))
    {
        case Ci.nsIPrefBranch.PREF_BOOL:
            return function() prefs.getBoolPref(name);
        case Ci.nsIPrefBranch.PREF_INT:
            return function() prefs.getIntPref(name);
        case Ci.nsIPrefBranch.PREF_STRING:
            if (isPrefDefaultLocalizedString(prefs.root + name))
                return function() prefs.getComplexValue(name, Ci.nsIPrefLocalizedString).data;
            else
                return function() prefs.getComplexValue(name, Ci.nsISupportsString).data;
        default:
            throw new Error("unknown pref type: " + prefs.getPrefType(name) + " (" + prefs.root + name + ")");
    }
}


function isPrefDefaultLocalizedString(name)
{
    var defaults = Services.prefs.getDefaultBranch(name);
    var defaultValue = defaults.getComplexValue("", Ci.nsISupportsString).data;
    var result = /^chrome:\/\/.+\/locale\/.+\.properties$/.test(defaultValue);
    return result;
}


function cachedGetter(getter, name)
{
    return function()
    {
        if (! (name in this))
            this[name] = getter();
        return this[name];
    }
}


function PreferencesProxy(branch, pref2prop)
// extends ListenerManager
// implements nsIObserver
{
    ListenerManager.call(this);
    
    var prefs = Services.prefs.getBranch(branch);
    prefs.addObserver("", this, true);  // weak reference
    
    this._pref2prop = {};
    for each (let [prefName, propName] in Iterator(pref2prop))
    {
        var hasPropName = (typeof(propName) == "string");
        propName = (hasPropName ? propName : prefName.replace(/\.\w/g, function(s) s[1].toUpperCase()));
        
        this._pref2prop[prefName] = propName;
        this.__defineGetter__(propName, cachedGetter(prefGetter(prefs, prefName), "_" + propName));
    }
}

PreferencesProxy.prototype =
{
    QueryInterface: XPCOMUtils.generateQI([
        Ci.nsIObserver,
        Ci.nsISupports,
        Ci.nsISupportsWeakReference]),
    
    // nsIObserver
    observe: function(subject, topic, data)
    {
        var propName = this._pref2prop[data];
        if (propName)
        {
            delete this["_" + propName];
            this.notifyListeners(this, propName);
        }
    }
}

extend(PreferencesProxy, ListenerManager);


function PreferenceProxy(prefName)
// extends PreferencesProxy
{
    PreferencesProxy.call(this, prefName, {"": "value"});
}

extend(PreferenceProxy, PreferencesProxy);
